package com.haodai.vip.tomcat.server.controller;

import com.haodai.vip.tomcat.server.*;

import java.io.File;
import java.util.List;

/**
 * Created by huangtao on 17/5/31.
 */
public class HeaderAndParamaController implements Servlet {

    @Override
    public void get(Request request, Response response) throws Exception {
        response.write("get请求 来自于"+request.getHost()+"<br/><br/><br/>");
        printRequestHeader(request, response);
        response.write("<br/><br/>");
        printRequestParamter(request, response);
        response.addCookie("name", "lalala", 10);
        response.addCookie("age", "27", 20);
        response.write("<br/><br/>");
        prinRequestCookie(request, response);
        HttpSession session = request.getSession(response);
        session.put("name", "黄涛");
    }



    @Override
    public void post(Request request, Response response) throws Exception {
        response.write("post请求 来自于"+request.getHost()+"<br/><br/><br/>");
        printRequestHeader(request, response);
        printRequestParamter(request, response);
        response.addCookie("name", "lalala", 10);
        response.addCookie("age", "27", 20);
        prinRequestCookie(request, response);
    }

    private void prinRequestCookie(Request request, Response response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            response.write("Cookie信息：<br/>");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                response.write("&nbsp;&nbsp;&nbsp;&nbsp;"+cookie.name+": "+cookie.value+"<br/>");
            }
        }
    }

    private void printRequestHeader(Request request, Response response) {
        List<String> headerNameList = request.getHeaderNames();
        response.write("Header信息：<br/>");
        for (int i = 0; i < headerNameList.size(); i++) {
            String name = headerNameList.get(i);
            String header = request.getHeader(name);
            response.write("&nbsp;&nbsp;&nbsp;&nbsp;"+name+": "+header+"<br/>");
        }
    }

    private void printRequestParamter(Request request, Response response) {
        List<String> paramNameList = request.getParamsNames();
        response.write("params：<br/>");
        for (int i = 0; i < paramNameList.size(); i++) {
            String name = paramNameList.get(i);

            Object param = request.getParam(name);

            if (param instanceof String){
                response.write("&nbsp;&nbsp;&nbsp;&nbsp;"+name+": "+param+"<br/>");
            } else {
                File file = (File) param;
                response.write("&nbsp;&nbsp;&nbsp;&nbsp;"+name+": 文件大小-->"+file.getPath()+"<br/>");
            }

        }
    }

}
